package com.j180.service;

import com.j180.bean.Customer;
import com.j180.dao.ICustomerDao;
import com.j180.util.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class CustomerServiceImpl implements  ICustomerService{

     private SqlSession sqlSession =SqlSessionUtil.getSqlSession();

    @Override
    public List<Customer> showAllCustomersInfo() {

        try {
            ICustomerDao iCustomerDao = sqlSession.getMapper(ICustomerDao.class);

            List<Customer> list = iCustomerDao.getAllCustomers();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
        return null;
    }

    @Override
    public Customer showCustomerById(int id) {

        try {
            ICustomerDao iCustomerDao = sqlSession.getMapper(ICustomerDao.class);

            Customer customer =  iCustomerDao.getCustomerById(id);

            return customer;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
        return null;
    }

    @Override
    public int addCustomerInfo(Customer customer) {

        try {
            ICustomerDao iCustomerDao = sqlSession.getMapper(ICustomerDao.class);

            int num = iCustomerDao.addCustomer(customer);

            sqlSession.commit();

            return num;
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
        } finally {
            sqlSession.close();
        }

        return 0;
    }

    @Override
    public int deleteCustomerInfo(int id) {

        try {
            ICustomerDao iCustomerDao = sqlSession.getMapper(ICustomerDao.class);

            int num = iCustomerDao.deleteCustomer(id);

            sqlSession.commit();
            return num;
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
        } finally {
            sqlSession.close();
        }

        return 0;
    }

    @Override
    public int updateCustomerInfo(Customer customer) {


        try {
            ICustomerDao iCustomerDao = sqlSession.getMapper(ICustomerDao.class);

            int num = iCustomerDao.updateCustomer(customer);
            sqlSession.commit();
            return num;
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
        } finally {
            sqlSession.close();
        }
        return 0;
    }
}
